package com.shamp.shop.basic.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.shamp.shop.basic.form.UserForm;
import com.shamp.shop.basic.model.Person;
import com.shamp.shop.basic.model.User;
import com.shamp.shop.basic.service.UserService;

@Controller
@RequestMapping("/user/")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	private static final String VN_REG_FORM = "registrationForm";
	private static final String VN_REG_OK = "registrationOk";
	
	
	@Autowired
	UserService userService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setAllowedFields(new String[] {
					"userName", "password", "confirmPassword", "firstName",
					"lastName", "email", "acceptTerms" , "enabled"});
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
		}
	
	
	@RequestMapping(value="register", method = RequestMethod.GET)
	public String getRegistrationForm(Model model){
		logger.info("directing to registration page");
		model.addAttribute("user", new UserForm());
		return "registrationForm";
	}
	
	@RequestMapping(method=RequestMethod.GET,value="registeredMembersList.htm")
	public ModelAndView listPeople() {
		logger.debug("Received request to list regsitered members");
		ModelAndView mav = new ModelAndView();
		Iterable<User> userList = userService.getUsers();
		System.out.println(userList.toString());
		mav.addObject("userList",userList);
		mav.setViewName("regMembersList");
		return mav;
		
	}
	
	@RequestMapping(value = "users.html", method = RequestMethod.POST)
	public String postRegistrationForm(//7User user,
			 @Valid @ModelAttribute(value = "user") UserForm form,BindingResult result){
		logger.info(" postRegistrationForm userName:"+form.getUserName());
		convertPasswordError(result);
		//accountService.registerAccount(toAccount(form), form.getPassword(), result);
		userService.createUser(toUser(form), form.getPassword(), result);
		logger.info("Registering User");
		return (result.hasErrors() ? VN_REG_FORM : VN_REG_OK);
		//return "registrationOk";
		
	}
	
	private static void convertPasswordError(BindingResult result) {
		// Map class-level Hibernate error message to field-level Spring error message.
		for (ObjectError error : result.getGlobalErrors()) {
			String msg = error.getDefaultMessage();
			if ("user.password.mismatch.message".equals(msg)) {
				// Don't show if there's already some other error message.
				if (!result.hasFieldErrors("password")) {
					result.rejectValue("password", "error.mismatch");
				}
			}
		}
	}
	private static User toUser(UserForm form) {
		User user = new User();
		user.setUserName(form.getUserName());
		user.setFirstName(form.getFirstName());
		user.setLastName(form.getLastName());
		user.setEmail(form.getEmail());
		user.setAcceptTerms(form.getAcceptTerms());
		user.setEnabled(form.isEnabled());
		return user;
	}
}
